/*
 * Copyright (C) 2007 ETH Zurich
 *
 * This file is part of Fosstrak (www.fosstrak.org).
 *
 * Fosstrak is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License version 2.1, as published by the Free Software Foundation.
 *
 * Fosstrak is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with Fosstrak; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA  02110-1301  USA
 */
package com.qf.cx.simplenms.subscriber.type;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.http.HttpStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import com.qf.cx.simplenms.report.model.Report;
import com.qf.cx.simplenms.subscriber.api.HttpChannel;
import com.qf.cx.simplenms.subscriber.impl.HttpChannelImpl;
import com.qf.cx.simplenms.subscriber.type.exception.InvalidURIException;

/**
 * send message as HTTP POST request using a standard socket.
 * 
 * @author swieland
 */
public class HTTPSubscriberOutputChannel extends AbstractSocketSubscriberOutputChannel {

	private Logger logger = LoggerFactory.getLogger(this.getClass());
	/** default port */
	private static final int DEFAULT_PORT = 80;

	private final URL url;
	private final String host;
	private final int port;
	private final String path;

	private final HttpChannel httpChannel;

	public HTTPSubscriberOutputChannel(String notificationURI) throws InvalidURIException {
		try {
			url = new URL(notificationURI);
			host = url.getHost();
			port = (url.getPort() == -1) ? DEFAULT_PORT : url.getPort();
			path = StringUtils.startsWithIgnoreCase(url.getPath(), "/") ? url.getPath().substring(1) : url.getPath();
			httpChannel = new HttpChannelImpl(notificationURI);
		} catch (MalformedURLException e) {
			logger.error("malformed URL: ", e);
			throw new InvalidURIException("malformed URL: ", e);
		}
	}

	@Override
	public boolean push(Report report) {
		logger.debug("Write reports '" + report + "' as post request to http socket '" + getHost() + ":" + getPort() + "'.");
		String content = getPostRequest(report);
		try {
			int statusCode = httpChannel.post(content);
			if (statusCode != HttpStatus.SC_OK) {
				logger.error("send report to {} failed, status code = {}", url, statusCode);
				return false;
			}
		} catch (IOException e) {
			logger.error("send report to {} failed", url, e);
			return false;
		}
		return true;
	}

	private String getPostRequest(Report report) {
		return getJson(report);
	}

	@Override
	public String getHost() {
		return host;
	}

	@Override
	public int getPort() {
		return port;
	}

	public String getPath() {
		return path;
	}

	@Override
	public String toString() {
		return url.toString();
	}
	
	@Override
	public void close() {
		httpChannel.close();
	}

}
